package com.molin.setTest;

import java.util.TreeSet;
/*
* 按照年龄从小到大排，如果年龄一样，则按照姓名首字母排序。
* 如果姓名和年龄一样，才认为是同一个学生对象，不存入。*/

public class MyTreeSet2 {
    public static void main(String[] args) {
//        treeSet_Interger();
        TreeSet<Student> studentTreeSet=new TreeSet<>();
        studentTreeSet.add(new Student(23,"xiaoli"));
        studentTreeSet.add(new Student(25,"xiaowang"));
        studentTreeSet.add(new Student(24,"xiaoming"));
        studentTreeSet.add(new Student(24,"xiaoming"));
        studentTreeSet.add(new Student(24,"xiaohei"));
        System.out.println(studentTreeSet);
    }

    static class Student implements Comparable<Student>{
        private int age;
        private String name;

        public Student(int age, String name) {
            this.age = age;
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "age=" + age +
                    ", name='" + name + '\'' +
                    '}';
        }

        @Override
        public int compareTo(Student o) {
            int result=this.age-o.age;
            /*string.compareTo
            如果参数字符串等于此字符串，则返回值 0；
            如果此字符串小于字符串参数，则返回一个小于 0 的值；
            如果此字符串大于字符串参数，则返回一个大于 0 的值。*/
            //年龄相等按照字母大小进行排序
           return result==0?this.name.compareTo(o.getName()):result;
        }
    }

    public static void treeSet_Interger() {
        //TreeSet存储Integer类型
        TreeSet<Integer> ts=new TreeSet<>();
        ts.add(5);
        ts.add(4);
        ts.add(3);
        ts.add(0);
        ts.add(10);
        System.out.println(ts);
        //[0, 3, 4, 5, 10]
    }
}